import { message } from "antd";
import { cloneDeep, merge } from "lodash";
import { hashHistory } from "dva/router";
import {
  advertisementAudit,
  queryAllAddress,
  getDetail,
  AllEstateList,
  allActivityList,
  submit,
  getDiscity,
} from "./popScreenAdDetailServ.js";
import { makeAddress } from "utils/util";
import moment from "moment";
const delay = (ms) =>
  new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
const defultState = {
  //推荐楼盘
  query: {
    provinceCodes: [""],
    cityCodes: [[]],
    wholeCountry: false,
    imgUrl: [],
    cityNames: [[]],
  },
  clique: "",
  city: [],
  actionType: "",
  areaList1: [],
  projectList: [],
  visible: false,
  value: 1,
  local: false,
  num: "",
  channelIndex: 1,
  biz: {
    1: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    2: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    3: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    4: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    5: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    6: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    7: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    9: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    10: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    11: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    12: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    13: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
  },
  biz2: {
    queryForm: {},
    rowSelection_type: "radio",
  },
  hrefModalObj: {
    visible: false,
    hrefType: "",
  },
  currentItem: [],
  clique: "",
  btnLoading: false,
  discityList: [],
  confirmAudit: false,
  ignoreReason: false,
  auditDesc: "", //驳回原因
  // 加载中状态
  loadingGroup: {
    '0': false,
    "-1": false,
    '1': false,
    '2': false,
  },
};

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      let clique = localStorage.getItem("clique");
      history.listen(({ pathname, query }) => {
        console.log(query);
        if ("" + tmpModule.pathname === "" + pathname) {
          dispatch({ type: "updateStore", payload: cloneDeep(defultState) });
          dispatch({
            type: "updateStore",
            payload: {
              actionType: query.actionType,
              advertisingId: query.advertisingId,
              clique: localStorage.getItem("clique"),
            },
          });
          dispatch({ type: "getAreaList", payload: {} });
          // dispatch({type: 'getAllEstateList'})
        }
      });
    },
  },

  effects: {
    //获取省市
    *getAreaList({ payload }, { put, call, select }) {
      let { actionType, advertisingId, clique } = yield select(
        (state) => state[tmpModule.namespace]
      );
      const { data, success } = yield call(queryAllAddress);
      if (success) {
        let arr = [];
        data.map((item, index) => {
          arr.push(item.value);
        });
        let areaList1 = [];
        if (JSON.parse(clique)) {
          let arr = [data[0]];
          let attr = [data[data.length - 1]];
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr,
          };
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr,
          };
        }
        // //去掉第三级，
        // areaList = makeAddress(data,2)
        areaList1 = makeAddress(data, 2);
        areaList1 = data;
        areaList1.shift();
        yield put({
          type: "updateStore",
          payload: { areaList1, roleArea: arr },
        });
        if (actionType == "detail" || actionType == "edit") {
          yield put({ type: "getDetail", payload: { advertisingId } });
        }
      }
    },
    //获取活动详细信息
    *getDetail({ payload }, { put, call, select }) {
      console.log(payload);
      const { data, success } = yield call(getDetail, payload);

      if (success) {
        //回来的数据回显
        //
        let { city, areaList1, currentItem, roleArea } = yield select(
          (state) => state[tmpModule.namespace]
        );
        console.log(areaList1);

        let hrefModalObj = {};
        hrefModalObj.linkUrl = data.linkUrl;
        hrefModalObj.hrefType = data.linkType;
        hrefModalObj.btnName = data.btnName;
        if (data.wholeCountry) {
          data.provinceCodes = ["0"];
          data.cityCodes = [];
        } else {
          for (var i = 0; i < data.provinceCodes.length; i++) {
            // console.log(query.provinceCodes[i])
            if (roleArea.indexOf(data.provinceCodes[i]) == -1) {
              delete data.provinceCodes[i];
            }
            for (var y = 0; y < areaList1.length; y++) {
              // console.log(areaList1[y])
              if (data.provinceCodes[i] == areaList1[y].value) {
                city[i] = areaList1[y].children;
                // console.log(areaList1[y])
              }
            }
            city.map((item) => {
              item.map((child) => {
                child.disabled = true;
              });
            });
          }
        }
        console.log(data);
        console.log("==================================");
        console.log(city);
        //(1:推介 2：内部链接 3：资讯 4:外部链接 5：活动，6：预约看房，7：美房详情)
        if (["1", "6", "7"].indexOf(data.linkType + "") > -1) {
          currentItem = [data.productId];
        } else if (["5", "3"].indexOf(data.linkType + "") > -1) {
          currentItem = [data.contentId];
        } else if (["2"].indexOf(data.linkType + "") > -1) {
          currentItem = data.linkUrl && [data.linkUrl.split("=")[1]];
        }
        if (data.url) {
          data.imgUrl = data.url;
          delete data.url;
        }
        // if(data.startTime){
        //   data.startDate = data.startTime
        //   delete data.startTime
        // }
        // if(data.endTime){
        //   data.endDate = data.endTime
        //   delete data.endTime
        // }
        hrefModalObj.params = {
          contentId: data.contentId,
          productId: data.productId,
          btnName: data.btnName,
        };
        console.log(hrefModalObj);
        // console.log(city)
        yield put({
          type: "getActivityList",
          payload: { businessId: data.productId },
        });
        yield put({
          type: "updateStore",
          payload: { city, query: data, hrefModalObj, currentItem },
        });
      }
    },
    *getDiscity({ payload }, { put, call, select }) {
      let pId = payload.pId;
      let { discityList } = yield select((state) => state[tmpModule.namespace]);
      let { success, rows } = yield call(getDiscity, pId);
      if (success) {
        let arr = rows
          .filter((item) => {
            return false;
          })
          .map((item) => item.cityCode);
        yield put({
          type: "updateStore",
          payload: { discityList: [...discityList, ...arr] },
        });
        console.log([...discityList, ...arr]);
      }
    },

    //提交表单
    *submit({ payload }, { put, call, select }) {
      if (JSON.stringify(payload) == "{}") {
        yield put({ type: "updateStore", payload: { btnLoading: true } });
      }
      let { query, hrefModalObj, actionType, areaList1, city } = yield select(
        (state) => state[tmpModule.namespace]
      );
      let objParmas = {};
      if (query.imgUrl.length == 0) {
        message.error("请上传轮播图图片");
        yield put({ type: "updateStore", payload: { btnLoading: false } });
        return false;
      }
      if (
        !query.wholeCountry &&
        new Date(query.endTime).getTime() -
        new Date(query.startTime).getTime() >
        15 * 24 * 3600 * 1000
      ) {
        if (
          new Date(query.endTime).getTime() -
          new Date(query.startTime).getTime() >
          15 * 24 * 3600 * 1000
        ) {
          yield put({ type: "updateStore", payload: { btnLoading: false } });
          message.error("设置生效日期的范围最长不能超过15天");
          return false;
        }
      }

      let params = hrefModalObj.params;
      query.linkType = hrefModalObj.hrefType;
      objParmas = {
        ...cloneDeep(query),
        ...cloneDeep(hrefModalObj),
        ...params,
      };
      if (objParmas.seckillActivityId) {
        delete objParmas.seckillActivityId;
      }
      let province = [],
        mcity = [];
      if (!objParmas.wholeCountry) {
        if (objParmas.provinceCodes && objParmas.provinceCodes.length) {
          objParmas.provinceCodes.map((item) => {
            areaList1.map((child) => {
              if (child.value == item) {
                province.push(child.label);
              }
            });
          });
        }
        if (objParmas.cityCodes && objParmas.cityCodes.length) {
          objParmas.cityCodes.map((item, index) => {
            item.map((child) => {
              city.map((son) => {
                son.map((k) => {
                  if (k.value == child) {
                    mcity.push(k.label);
                  }
                });
              });
            });
          });
        }

        if (mcity.length) {
          if (mcity.length < 3) {
            objParmas.city = mcity.join(",");
          } else {
            objParmas.city = mcity.splice(0, 3).join(",") + "等";
          }
        }
        let pList = [],
          nList = [];
        city.map((item, index) => {
          if (
            objParmas.cityCodes[index] &&
            objParmas.cityCodes[index].length == city[index].length
          ) {
            areaList1.map((child) => {
              if (child.value == objParmas.provinceCodes[index]) {
                pList.push(child.label);
              }
            });
          } else {
            objParmas.cityCodes[index].map((item) => {
              city[index].map((child) => {
                if (child.value == item) {
                  nList.push(child.label);
                }
              });
            });
          }
        });
        if (nList.length >= 3) {
          nList = nList.splice(0, 3).join("、") + "等多个城市";
        } else {
          nList = nList.length ? "及" + nList.join("、") + "等城市" : "";
        }
        if (pList.length) {
          objParmas.city = `${pList.join(",")}${nList}`;
        }
      } else {
        objParmas.city = "全国";
      }

      if (objParmas.wholeCountry || objParmas.location == "2") {
        delete objParmas.provinceCodes;
        delete objParmas.cityCodes;
      }
      if (objParmas.imgUrl) {
        objParmas.url = objParmas.imgUrl;
        delete objParmas.imgUrl;
      }
      console.log(objParmas);
      const { success, msg } = yield call(submit, { ...objParmas });
      if (success) {
        // if (moment(query.startDate).isAfter(moment().add(10, 'minutes'))) {
        //   message.success(`您设置的弹窗广告将在${query.startDate}后10分钟内生效，请关注`);
        // } else {
        //   message.success(`您设置的弹窗广告将在10分钟之内生效，请稍候`);
        // }
        //message.success(actionType=='add'?'新增成功':'编辑成功')
        if (JSON.stringify(payload) != "{}" && payload.AuditOk) {
          let advertisingId = msg;
          yield put({
            type: "advertisementAuditsubmit",
            payload: { advertisingId, auditStatus: 1 },
          });
        } else {
          message.success(actionType == "add" ? "新增成功" : "编辑成功");
          hashHistory.push("/home/advertisementAdmin/popScreenAdList?closeTab=true");
        }
        // hashHistory.push('/home/advertisementAdmin/popScreenAdList')
      }
      yield call(delay, 2000);
      yield put({ type: "updateStore", payload: { btnLoading: false } });
    },
    //获取所有上架楼盘列表
    *getAllEstateList({ payload }, { put, call, select }) {
      let { projectList } = yield select((state) => state[tmpModule.namespace]);
      const { rows, success, total, pageNo } = yield call(AllEstateList, {
        shelfStatus: "1",
        pageSize: 100000,
      });
      if (success) {
        yield put({
          type: "updateStore",
          payload: {
            projectList: rows,
            projectListTotal: total,
            projectListPageNo: pageNo,
          },
        });
      }
    },
    //获取当前楼盘的活动或资讯列表
    *getActivityList({ payload }, { put, call, select }) {
      console.log(payload);
      const { rows, success, total, pageNo } = yield call(allActivityList, {
        ...payload,
        pageSize: 10000,
        status: 1,
      });
      if (success) {
        console.log(rows);
        yield put({ type: "updateStore", payload: { activityList: rows } });
      }
    },
    // 审核
    *advertisementAuditsubmit({ payload }, { put, call, select }) {
      try {
        let { loadingGroup } = yield select(
          (state) => state[tmpModule.namespace]
        );
        loadingGroup["" + payload.auditStatus + ""] = true;
        yield put({
          type: "updateStore",
          payload: { loadingGroup: loadingGroup },
        });
        const { success } = yield call(advertisementAudit, payload);
        if (success) {
          message.success("操作成功");
          hashHistory.push("/home/advertisementAdmin/popScreenAdList?closeTab=true");
          // put({type: 'getDetail', payload: {advertisementId}})
        }
        loadingGroup["" + payload.auditStatus + ""] = false;
        yield put({
          type: "updateStore",
          payload: { loadingGroup: loadingGroup },
        });
      } catch (error) {
        console.log(error);
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload);
    },
  },
};
export default tmpModule;
